<!doctype html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
    
  
  <link href="//cdn.jsdelivr.net/fancybox/2.1.5/jquery.fancybox.min.css" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






  

<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.6.2/css/font-awesome.min.css" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.0" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="多线程,java," />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.0" />






<meta name="description" content="前言此文是笔者学习了慕课网《细说Java多线程之内存可见性》教程而记录的，若想学习该课程请走传送门
学习目标：

共享变量在线程间的可见性
synchronized实现可见性
volatile实现可见性
指令重排序
as-if-serial语义
volatile使用注意事项
synchronized 和volatile比较

JMM–Java内存模型
共享变量可见性实现原理线程1对共享变量的修改要">
<meta property="og:type" content="article">
<meta property="og:title" content="细说Java多线程之内存可见性">
<meta property="og:url" content="https://zitongchen.github.io/2017/08/10/细说Java多线程之内存可见性/index.html">
<meta property="og:site_name" content="Tony's Notes">
<meta property="og:description" content="前言此文是笔者学习了慕课网《细说Java多线程之内存可见性》教程而记录的，若想学习该课程请走传送门
学习目标：

共享变量在线程间的可见性
synchronized实现可见性
volatile实现可见性
指令重排序
as-if-serial语义
volatile使用注意事项
synchronized 和volatile比较

JMM–Java内存模型
共享变量可见性实现原理线程1对共享变量的修改要">
<meta property="og:image" content="https://static.oschina.net/uploads/img/201708/13171116_n5Dd.png">
<meta property="og:image" content="https://static.oschina.net/uploads/img/201708/13171654_mdpg.png">
<meta property="og:updated_time" content="2017-09-16T10:26:33.301Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="细说Java多线程之内存可见性">
<meta name="twitter:description" content="前言此文是笔者学习了慕课网《细说Java多线程之内存可见性》教程而记录的，若想学习该课程请走传送门
学习目标：

共享变量在线程间的可见性
synchronized实现可见性
volatile实现可见性
指令重排序
as-if-serial语义
volatile使用注意事项
synchronized 和volatile比较

JMM–Java内存模型
共享变量可见性实现原理线程1对共享变量的修改要">
<meta name="twitter:image" content="https://static.oschina.net/uploads/img/201708/13171116_n5Dd.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":0,"b2t":false,"scrollpercent":false},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://zitongchen.github.io/2017/08/10/细说Java多线程之内存可见性/"/>





  <title> 细说Java多线程之内存可见性 | Tony's Notes </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  














  
  
    
  

  <div class="container one-collumn sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Tony's Notes</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="https://zitongchen.github.io/2017/08/10/细说Java多线程之内存可见性/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Tony">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avater.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Tony's Notes">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                细说Java多线程之内存可见性
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-08-10T00:00:00+08:00">
                2017-08-10
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Java/" itemprop="url" rel="index">
                    <span itemprop="name">Java</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/2017/08/10/细说Java多线程之内存可见性/" class="leancloud_visitors" data-flag-title="细说Java多线程之内存可见性">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数 </span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h1><p>此文是笔者学习了慕课网《细说Java多线程之内存可见性》教程而记录的，若想学习该课程请走<a href="http://www.imooc.com/learn/352" target="_blank" rel="external">传送门</a></p>
<p>学习目标：</p>
<ul>
<li>共享变量在线程间的可见性</li>
<li>synchronized实现可见性</li>
<li>volatile实现可见性</li>
<li>指令重排序</li>
<li>as-if-serial语义</li>
<li>volatile使用注意事项</li>
<li>synchronized 和volatile比较</li>
</ul>
<h1 id="JMM–Java内存模型"><a href="#JMM–Java内存模型" class="headerlink" title="JMM–Java内存模型"></a>JMM–Java内存模型</h1><p><img src="https://static.oschina.net/uploads/img/201708/13171116_n5Dd.png" alt="输入图片说明" title="在这里输入图片标题"></p>
<h2 id="共享变量可见性实现原理"><a href="#共享变量可见性实现原理" class="headerlink" title="共享变量可见性实现原理"></a>共享变量可见性实现原理</h2><p>线程1对共享变量的修改要想被线程2及时看到，必须要经过一下2个步骤：</p>
<ul>
<li>把工作内存1中更新过的共享变量刷新到主内存中</li>
<li>将主内存中最新的共享变量的值更新到工作内存2中</li>
</ul>
<p><img src="https://static.oschina.net/uploads/img/201708/13171654_mdpg.png" alt="输入图片说明" title="在这里输入图片标题"></p>
<h1 id="可见性"><a href="#可见性" class="headerlink" title="可见性"></a>可见性</h1><p>可见性：一个线程对共享变量值的修改，能够及时地被其他线程看到</p>
<p>共享变量：如果一个变量在多个线程的工作内存中存在副本，那么这个变量就是这几个线程的共享变量。</p>
<p>Java内存模型(Java Memory Modal)描述了java程序中各种变量（线程共享变量）的访问规则，以及在JVM中将变量存储到内存中和从内存中读取出变量这些底层的细节。针对共享变量而规范起来。</p>
<ul>
<li>所以的变量都存储在主内存中</li>
<li>每个线程都有自己独立的工作内存，里面保存该线程使用到的变量的副本（主内存中该变量的一份拷贝）</li>
</ul>
<p>两条规定：</p>
<ul>
<li>线程对共享变量的所以操作都必须在自己工作内存中进行，不能直接从主内存中读写</li>
<li>不同线程之间无法直接访问其他线程工作内存中的变量，线程间变量的值传递需要通过主内存来完成。</li>
</ul>
<p>要实现共享变量的可见性，必须保证两点：</p>
<ul>
<li>线程修改后的共享变量值能及时从工作内容刷新到主内存中</li>
<li>其他线程能够及时把共享变量的最新值从主内存更新到自己的工作内存中</li>
</ul>
<h2 id="重排序"><a href="#重排序" class="headerlink" title="重排序"></a>重排序</h2><p>重排序：代码书写的顺序与实际执行的顺序不同，指令重排序是编译器或处理器为了提高程序性能而做的优化，具有数据依赖的程序段，不会进行重排序</p>
<ol>
<li>编辑器优化的重排序（编译器优化）</li>
<li>指令级并行中排序（处理器优化）</li>
<li>内存系统的重排序（处理器优化）</li>
</ol>
<h2 id="as-if-serial"><a href="#as-if-serial" class="headerlink" title="as-if-serial"></a>as-if-serial</h2><figure class="highlight plain"><table><tr><td class="code"><pre><div class="line">int num1 = 1;  // 第一行代码</div><div class="line">int num2 = 2;  // 第二行代码</div><div class="line">int sum = num1 + num2;  // 第三行代码</div></pre></td></tr></table></figure>
<p><strong>单线程：第1，2行的顺序可以重排，但第3行不行</strong></p>
<p><strong>重排序不会给单线程带来内存可见性问题</strong></p>
<p><strong>多线程中程序交错执行时，重排序可能会造成内存可见性问题</strong></p>
<h2 id="可见性分析"><a href="#可见性分析" class="headerlink" title="可见性分析"></a>可见性分析</h2><figure class="highlight plain"><table><tr><td class="code"><pre><div class="line">// 共享变量</div><div class="line">private boolean ready = false;</div><div class="line">private int result = 0;</div><div class="line">private int number = 1;</div><div class="line">// 写操作</div><div class="line">public void write() &#123;</div><div class="line">    ready = true;  // 1.1</div><div class="line">    number  = 2;  // 1.2</div><div class="line">&#125;</div><div class="line">// 读操作</div><div class="line">public void read() &#123;</div><div class="line">    if (ready) &#123;                            // 2.1</div><div class="line">            result = number * 3;  // 2.2</div><div class="line">        &#125;</div><div class="line">    System.out.println(&quot;result的值为：&quot; + result);</div><div class="line">&#125;</div><div class="line">/**</div><div class="line">执行顺序：1.2 --&gt; 2.1 --&gt; 2.2 --&gt; 1.1</div><div class="line">输出的结果为：result的值为：0</div><div class="line">**</div></pre></td></tr></table></figure>
<p>导致共享变量在线程间不可见的原因：</p>
<ol>
<li>线程的交叉执行</li>
<li>重排序结合线程交叉执行</li>
<li>共享变量更新后的值没有在工作内存与主内存间及时更新</li>
</ol>
<h1 id="synchronized实现可见性"><a href="#synchronized实现可见性" class="headerlink" title="synchronized实现可见性"></a>synchronized实现可见性</h1><p>Java语言层面支持的可见性实现方式：</p>
<ul>
<li>synchronized</li>
<li>volatile</li>
</ul>
<p>synchronized能够实现：</p>
<ul>
<li>原子性（同步）</li>
<li>可见性<br>JMM关于synchronized的两条规定：</li>
</ul>
<ul>
<li>线程解锁前，必须把共享变量的最新值刷新到主内存中</li>
<li>线程加锁时，将清空工作内存中的共享变量的值，从而使用共享变量时需要从主内存中重新读取最新值（注意：加锁与解锁需要是同一把锁）</li>
</ul>
<p>synchronized实现可见性时，线程执行互斥代码的过程：</p>
<ol>
<li>获得互斥锁</li>
<li>清空工作内存</li>
<li>从主内存拷贝变量的最新副本到工作内存中</li>
<li>执行代码</li>
<li>将更改后的共享变量的值刷新到主内存</li>
<li>释放互斥锁</li>
</ol>
<p>线程解锁前对共享变量的修改在下次加锁时对其他线程可见</p>
<p>编译器在不使用synchronized也可以实现变量的可见性，但不能完全确保</p>
<h1 id="volatile实现可见性"><a href="#volatile实现可见性" class="headerlink" title="volatile实现可见性"></a>volatile实现可见性</h1><p>volatile关键字：</p>
<ul>
<li>能够保证volatile变量的可见性</li>
<li>不能保证volatile变量复合操作的原子性</li>
</ul>
<p>volatile如何实现内存可见性</p>
<p><strong>深入来说：通过加入内存屏障和禁止重排序优化来实现。</strong></p>
<ul>
<li>对volatile变量执行写操作时，会在写操作后加入一条store屏障指令</li>
<li>对volatile变量执行读操作时，会在读操作前加入一条load屏障指令<br>通俗地讲：volatile变量在每次被线程访问时，都强迫从主内存中重读该变量的值，而当该变量发生变化时，又会强迫线程将最新的值刷新到主内存中。这样任何时刻，不同的线程总能看到该变量的最新值。</li>
</ul>
<p>线程写volatile变量的过程：</p>
<ol>
<li>改变线程工作内存中volatile变量副本的值</li>
<li>将改变后副本的值从工作内存刷新到主内存</li>
</ol>
<p>线程读volatile变量的过程</p>
<ol>
<li>从主内存中读取volatile变量的最新值到线程的工作内存中</li>
<li>从工作内存中读取volatile变量的副本</li>
</ol>
<p>volatile不能保证volatile变量复合操作的原子性：<br><figure class="highlight plain"><table><tr><td class="code"><pre><div class="line">private int number = 0;</div><div class="line">number ++;  // 不是原子操作</div><div class="line">/**</div><div class="line">1.读取numbere的值</div><div class="line">2.将number的值加1</div><div class="line">3.写入最新的number的值</div><div class="line">**/</div><div class="line"></div><div class="line">//加入synchronized,变为原子操作</div><div class="line">synchronized(this) &#123;</div><div class="line">    number ++;</div><div class="line">&#125;</div><div class="line"></div><div class="line">//变量volatile变量，无法保证原子性</div><div class="line">private volatile int number = 0;</div></pre></td></tr></table></figure></p>
<h2 id="保证原子性的解决方案"><a href="#保证原子性的解决方案" class="headerlink" title="保证原子性的解决方案"></a>保证原子性的解决方案</h2><p><strong>程序分析</strong><br><figure class="highlight plain"><table><tr><td class="code"><pre><div class="line">private volatile int number = 5;</div></pre></td></tr></table></figure></p>
<ol>
<li>线程A读取number的值</li>
<li>线程B读取number的值</li>
<li>线程B执行加1操作</li>
<li>线程B写入最新的number的值</li>
<li>线程A执行加1操作</li>
<li>线程A写入最新的number值</li>
</ol>
<p><strong>最后：两次number++只增加了1</strong></p>
<p>保证number自增操作的原子性：</p>
<ul>
<li>使用synchronized关键字</li>
<li>使用ReentrantLock(java.until.concurrent.locks包下）</li>
<li>使用AtomicInterger(java.util.concurrent.atomic包下）</li>
</ul>
<h2 id="volatile的使用场景"><a href="#volatile的使用场景" class="headerlink" title="volatile的使用场景"></a>volatile的使用场景</h2><p>要在多线程中安全使用volatile变量，必须满足：</p>
<ol>
<li>对变量的写入操作不依赖当前值<ul>
<li>不满足：number ++ ,count = count * 5 等</li>
<li>满足：boolean变量，记录温度变化的变量</li>
</ul>
</li>
<li>该变量没有包含在具有其他不变式中<ul>
<li>不满足：不变式 low &lt; up</li>
</ul>
</li>
</ol>
<h1 id="synchronized-和-volatile比较"><a href="#synchronized-和-volatile比较" class="headerlink" title="synchronized 和 volatile比较"></a>synchronized 和 volatile比较</h1><ul>
<li>volatile不需要锁，比synchronized更轻量级，不会阻塞线程</li>
<li>从内存可见性角度将，volatile读相当于加锁，volatile写相当于解锁</li>
<li>synchronized即保证可见性，又能保证原子性，而volatile只能保证可见性，无法保证原子性</li>
</ul>
<p>synchronized类,在类中并没有使用synchronized加锁，因此会打印出不一样的结果。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Synchronized</span> </span>&#123;</div><div class="line">	<span class="comment">//共享变量</span></div><div class="line">    <span class="keyword">private</span> <span class="keyword">boolean</span> ready = <span class="keyword">false</span>;</div><div class="line">    <span class="keyword">private</span> <span class="keyword">int</span> result = <span class="number">0</span>;</div><div class="line">    <span class="keyword">private</span> <span class="keyword">int</span> number = <span class="number">1</span>;   </div><div class="line">    <span class="comment">//写操作</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">write</span><span class="params">()</span></span>&#123;</div><div class="line">    	ready = <span class="keyword">true</span>;	      			    <span class="comment">//1.1				</span></div><div class="line">    	number = <span class="number">2</span>;		                    <span class="comment">//1.2			    </span></div><div class="line">    &#125;</div><div class="line">    <span class="comment">//读操作</span></div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">read</span><span class="params">()</span></span>&#123;			   	 </div><div class="line">    	<span class="keyword">if</span>(ready)&#123;				        <span class="comment">//2.1</span></div><div class="line">    		result = number*<span class="number">3</span>;	 	<span class="comment">//2.2</span></div><div class="line">    	&#125;   	</div><div class="line">    	System.out.println(<span class="string">"result的值为："</span> + result);</div><div class="line">    &#125;</div><div class="line">    <span class="comment">//内部线程类</span></div><div class="line">    <span class="keyword">private</span> <span class="class"><span class="keyword">class</span> <span class="title">ReadWriteThread</span> <span class="keyword">extends</span> <span class="title">Thread</span> </span>&#123;</div><div class="line">    	<span class="comment">//根据构造方法中传入的flag参数，确定线程执行读操作还是写操作</span></div><div class="line">    	<span class="keyword">private</span> <span class="keyword">boolean</span> flag;</div><div class="line">    	<span class="function"><span class="keyword">public</span> <span class="title">ReadWriteThread</span><span class="params">(<span class="keyword">boolean</span> flag)</span></span>&#123;</div><div class="line">    		<span class="keyword">this</span>.flag = flag;</div><div class="line">    	&#125;</div><div class="line">        <span class="meta">@Override</span>                                                                    </div><div class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</div><div class="line">        	<span class="keyword">if</span>(flag)&#123;</div><div class="line">        		<span class="comment">//构造方法中传入true，执行写操作</span></div><div class="line">        		write();</div><div class="line">        	&#125;<span class="keyword">else</span>&#123;</div><div class="line">        		<span class="comment">//构造方法中传入false，执行读操作</span></div><div class="line">        		read();</div><div class="line">        	&#125;</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span>  </span>&#123;</div><div class="line">    	Synchronized synDemo = <span class="keyword">new</span> Synchronized();</div><div class="line">    	<span class="comment">//启动线程执行写操作</span></div><div class="line">    	synDemo.new ReadWriteThread(<span class="keyword">true</span>).start();</div><div class="line">    	<span class="comment">//启动线程执行读操作</span></div><div class="line">    	synDemo.new ReadWriteThread(<span class="keyword">false</span>).start();</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>使用了Lock实现了共享变量的原子性和可见性</p>
<figure class="highlight java"><table><tr><td class="code"><pre><div class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">VolatileDemo</span> </span>&#123;</div><div class="line">	<span class="keyword">private</span> Lock lock = <span class="keyword">new</span> ReentrantLock();</div><div class="line">	<span class="keyword">private</span> <span class="keyword">int</span> number = <span class="number">0</span>;</div><div class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">getNumber</span><span class="params">()</span></span>&#123;</div><div class="line">		<span class="keyword">return</span> <span class="keyword">this</span>.number;</div><div class="line">	&#125;</div><div class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">increase</span><span class="params">()</span></span>&#123;</div><div class="line">		<span class="keyword">try</span> &#123;</div><div class="line">			Thread.sleep(<span class="number">100</span>);</div><div class="line">		&#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</div><div class="line">			e.printStackTrace();</div><div class="line">		&#125;</div><div class="line">		lock.lock();</div><div class="line">		<span class="keyword">try</span> &#123;</div><div class="line">			<span class="keyword">this</span>.number++;</div><div class="line">		&#125; <span class="keyword">finally</span> &#123;</div><div class="line">			lock.unlock();</div><div class="line">		&#125;</div><div class="line">	&#125;</div><div class="line">	<span class="comment">/**</span></div><div class="line">	 * <span class="doctag">@param</span> args</div><div class="line">	 */</div><div class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</div><div class="line">		<span class="comment">// TODO Auto-generated method stub</span></div><div class="line">		<span class="keyword">final</span> VolatileDemo volDemo = <span class="keyword">new</span> VolatileDemo();</div><div class="line">		<span class="keyword">for</span>(<span class="keyword">int</span> i = <span class="number">0</span> ; i &lt; <span class="number">500</span> ; i++)&#123;</div><div class="line">			<span class="keyword">new</span> Thread(<span class="keyword">new</span> Runnable() &#123;</div><div class="line">				<span class="meta">@Override</span></div><div class="line">				<span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</div><div class="line">					volDemo.increase();</div><div class="line">				&#125;</div><div class="line">			&#125;).start();</div><div class="line">		&#125;</div><div class="line">		<span class="comment">//如果还有子线程在运行，主线程就让出CPU资源，</span></div><div class="line">		<span class="comment">//直到所有的子线程都运行完了，主线程再继续往下执行</span></div><div class="line">		<span class="keyword">while</span>(Thread.activeCount() &gt; <span class="number">1</span>)&#123;</div><div class="line">			Thread.yield();</div><div class="line">		&#125;</div><div class="line">		System.out.println(<span class="string">"number : "</span> + volDemo.getNumber());</div><div class="line">	&#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>


    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/多线程/" rel="tag"># 多线程</a>
          
            <a href="/tags/java/" rel="tag"># java</a>
          
        </div>
      

      
        
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/08/05/Java单元测试框架-JUnit4/" rel="next" title="Java单元测试框架-JUnit4">
                <i class="fa fa-chevron-left"></i> Java单元测试框架-JUnit4
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/08/13/UML学习笔记/" rel="prev" title="UML学习笔记">
                UML学习笔记 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>

          
          </div>
          


          
  <div class="comments" id="comments">
    
      <div id="uyan_frame"></div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/avater.png"
               alt="Tony" />
          <p class="site-author-name" itemprop="name">Tony</p>
           
              <p class="site-description motion-element" itemprop="description">学习技术，分享技术...</p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives">
                <span class="site-state-item-count">29</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">11</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">25</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/zitongchen" rel="external nofollow" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#前言"><span class="nav-number">1.</span> <span class="nav-text">前言</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#JMM–Java内存模型"><span class="nav-number">2.</span> <span class="nav-text">JMM–Java内存模型</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#共享变量可见性实现原理"><span class="nav-number">2.1.</span> <span class="nav-text">共享变量可见性实现原理</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#可见性"><span class="nav-number">3.</span> <span class="nav-text">可见性</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#重排序"><span class="nav-number">3.1.</span> <span class="nav-text">重排序</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#as-if-serial"><span class="nav-number">3.2.</span> <span class="nav-text">as-if-serial</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#可见性分析"><span class="nav-number">3.3.</span> <span class="nav-text">可见性分析</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#synchronized实现可见性"><span class="nav-number">4.</span> <span class="nav-text">synchronized实现可见性</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#volatile实现可见性"><span class="nav-number">5.</span> <span class="nav-text">volatile实现可见性</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#保证原子性的解决方案"><span class="nav-number">5.1.</span> <span class="nav-text">保证原子性的解决方案</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#volatile的使用场景"><span class="nav-number">5.2.</span> <span class="nav-text">volatile的使用场景</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#synchronized-和-volatile比较"><span class="nav-number">6.</span> <span class="nav-text">synchronized 和 volatile比较</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Tony</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io" rel="external nofollow">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next" rel="external nofollow">
    NexT.Mist
  </a>
</div>


        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    
    
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  




  
  <script type="text/javascript" src="//cdn.jsdelivr.net/jquery/2.1.3/jquery.min.js"></script>

  
  <script type="text/javascript" src="//cdn.jsdelivr.net/fastclick/1.0.6/fastclick.min.js"></script>

  
  <script type="text/javascript" src="//cdn.jsdelivr.net/jquery.lazyload/1.9.3/jquery.lazyload.min.js"></script>

  
  <script type="text/javascript" src="//cdn.jsdelivr.net/velocity/1.2.3/velocity.min.js"></script>

  
  <script type="text/javascript" src="//cdn.jsdelivr.net/velocity/1.2.3/velocity.ui.min.js"></script>

  
  <script type="text/javascript" src="//cdn.jsdelivr.net/fancybox/2.1.5/jquery.fancybox.pack.js"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.0"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.0"></script>



  



  




	





  





  
    

    
      <!-- UY BEGIN -->
      <script type="text/javascript" src="http://v2.uyan.cc/code/uyan.js?uid=2130825"></script>
      <!-- UY END -->
    
  





  



  
  

  

  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.1.js"></script>
  <script>AV.initialize("4wyUmphSKE5wrQGHEh5Js0bk-gzGzoHsz", "oTOHrhMuED5U0oqV2KrRMGF0");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  


  
</body>
</html>
